package com.my.test.ctrl.file;

import java.io.*;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/plupload")
public class PlUpload {

	@RequestMapping("/index")
	public String index(){
		return "plupload/index";
	}
	
	@RequestMapping(value="/upload" ,produces = "text/html; charset=utf-8")
    @ResponseBody
    public String dealUpload(HttpServletRequest request){
        if (ServletFileUpload.isMultipartContent(request)) {
            ServletFileUpload upload = new ServletFileUpload(
                    new DiskFileItemFactory());
            try {
                FileItemIterator iterator = upload.getItemIterator(request);
                File tmpDir = FileUtils.getTempDirectory();
                while (iterator.hasNext()) {
                    FileItemStream fileStream = iterator.next();
                    if (!fileStream.isFormField()){
                        String originFileName = fileStream.getName();
//                        String suffix = FileType.getSuffixByFilename(originFileName);
//                        String newFileName= MrandomUtil.getUUID()+suffix;
                        String path = tmpDir.getPath()+File.separator+originFileName;
                        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream( new File(path)));
                        BufferedInputStream bis = new BufferedInputStream(fileStream.openStream());
                        int count = 0;
                        byte[] dataBuf = new byte[ 2048 ];
                        while ((count = bis.read(dataBuf)) != -1) {
                            bos.write(dataBuf, 0, count);
                        }
                        bos.flush();
                        bos.close();
                        return path;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        throw new RuntimeException("上传文件出错了！！！");
    }
}
